<template>
    <div>
        <!-- 查询条件开始 -->
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="所属部门" prop="deptId">
                <el-select
                        v-model="queryParams.deptId"
                        placeholder="请选择部门"
                        clearable
                        size="small"
                        style="width:240px"
                >
                    <el-option
                            v-for="dict in deptOptions"
                            :key="dict.deptId"
                            :label="dict.deptName"
                            :value="dict.deptId"
                    />
                </el-select></el-form-item>
            <el-form-item label="用户姓名" prop="userName">
                <el-input
                        v-model="queryParams.userName"
                        placeholder="请输入用户姓名"
                        clearable
                        size="small"
                        style="width:240px"
                />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input
                        v-model="queryParams.phone"
                        placeholder="请输入手机号"
                        clearable
                        size="small"
                        style="width:240px"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                        v-model="queryParams.status"
                        placeholder="可用状态"
                        clearable
                        size="small"
                        style="width:240px"
                >
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                        v-model="queryParams.dateRange"
                        size="small"
                        style="width:240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholde="开始日期"
                        end-placeholde="结束日期"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="initUser" >搜索</el-button>

            </el-form-item>
        </el-form>

        <!-- 表格工具按钮开始 -->
        <el-row :gutter="10" style="margin-bottom: 8px;">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" >新增</el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delLists" >删除</el-button>
            </el-col>

        </el-row>
        <!-- 表格工具按钮结束 -->
        <!-- 数据表格开始 -->
        <el-table  border :data="userList"  @selection-change="handleSelectionChnage">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用户ID" align="center" prop="userId" />
            <el-table-column label="用户姓名" align="center" prop="userName" />
            <el-table-column label="部门" align="center" prop="deptId"  :formatter="deptFormat"/>
            <el-table-column label="手机号码【登陆身份】" width="180" align="center" prop="phone" />
            <el-table-column label="性别" align="center" prop="sex" :formatter="sexFormat" />
            <el-table-column label="年龄" align="center" prop="age"  />
            <el-table-column label="是否排班" align="center" prop="schedulingFlag" :formatter="schedulingFormat" />
            <el-table-column label="级别" prop="userRank" align="center" :formatter="levelFormat" />
            <el-table-column label="背景" prop="background" align="center" :formatter="backgroundFormat"/>
            <el-table-column label="状态" prop="status" align="center" :formatter="statusFormat"/>
            <el-table-column label="创建时间" align="center" prop="createTime" width="200"  />
            <el-table-column label="操作" align="center" width="250">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button  type="text" icon="el-icon-delete" size="mini" @click="delPro(scope.row.userId)">删除</el-button>
                    <el-button  type="text" icon="el-icon-thumb" size="mini" @click="fenRole(scope.row)">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 数据表格结束 -->
        <!-- 分页控件开始 -->
        <el-pagination
                v-show="total>0"
                :current-page="currentPage"
                :page-sizes="[5, 10, 20, 30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
        <!-- 分页控件结束 -->
        <!--分配角色的对话框-->

        <el-dialog title="提示" :visible.sync="dialogVisible" width="40%">
            <el-table
                    ref="roleListTable"
                    border
                    :data="roleTableList"
                    @selection-change="handleSelectionChange"
                    >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="角色ID" align="center" prop="roleId" />
                <el-table-column label="角色名称" align="center" prop="roleName" />
                <el-table-column label="权限编码" align="center" prop="roleCode" />
                <el-table-column label="备注" align="center" prop="remark" />
                <el-table-column label="创建时间" align="center" prop="createTime" />
            </el-table>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary"@click="confirmRole" >确 定</el-button>
          </span>
        </el-dialog>
        <!-- 添加修改弹出层开始 -->
        <el-dialog
                :title="title"
                :visible.sync="open"
                width="800px"
                center
                append-to-body
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="userName">
                            <el-input v-model="form.userName" style="width:240px" placeholder="请输入用户名称" clearable size="small" />
                        </el-form-item></el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="form.phone" style="width:240px" placeholder="请输入手机号，作为登陆凭证" clearable size="small" />
                        </el-form-item></el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属科室" prop="deptId">
                            <el-select
                                    v-model="form.deptId"
                                    placeholder="所属科室"
                                    clearable
                                    size="small"
                                    style="width:240px"
                            >
                                <el-option
                                        v-for="d in deptOptions"
                                        :key="d.deptId"
                                        :label="d.deptName"
                                        :value="d.deptId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="级别" prop="userRank">
                            <el-select
                                    v-model="form.userRank"
                                    placeholder="用户级别"
                                    clearable
                                    size="small"
                                    style="width:240px"
                            >
                                <el-option
                                        v-for="d in  levelOptions"
                                        :key="d.dictValue"
                                        :label="d.dictLabel"
                                        :value="d.dictValue"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="年龄" prop="age">
                            <el-input-number v-model="form.age" clearable size="small" :min="1"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="背景" prop="background">
                            <el-select
                                    v-model="form.background"
                                    placeholder="学历"
                                    clearable
                                    size="small"
                                    style="width:240px"
                            >
                                <el-option
                                        v-for="d in backgroudOptions"
                                        :key="d.dictValue"
                                        :label="d.dictLabel"
                                        :value="d.dictValue"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex">
                            <el-radio-group v-model="form.sex">
                                <el-radio
                                        v-for="d in sexOptions"
                                        :key="d.dictValue"
                                        :label="d.dictValue"
                                        :value="d.dictValue"
                                >{{ d.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                        v-for="dict in statusOptions"
                                        :key="dict.dictValue"
                                        :label="dict.dictValue"
                                        :value="dict.dictValue"
                                >{{ dict.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否参与排班" prop="schedulingFlag">
                            <el-radio-group v-model="form.schedulingFlag">
                                <el-radio
                                        v-for="d in schedulingOptions"
                                        :key="d.dictValue"
                                        :label="d.dictValue"
                                        :value="d.dictValue"
                                >{{ d.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email" style="width:240px" placeholder="请输入用户邮箱" clearable size="small" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="擅长" prop="strong">
                            <el-input v-model="form.strong" type="textarea" placeholder="请输入用户擅长" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="荣誉" prop="honor">
                            <el-input v-model="form.honor" type="textarea" placeholder="请输入用户相关荣誉" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="简介" prop="introduction">
                            <el-input v-model="form.introduction" type="textarea" placeholder="请输入用户简介" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>

        <el-button @click="cancel">取 消</el-button>
      </span>
        </el-dialog>
        <!-- 添加修改弹出层结束 -->
    </div>
</template>

<script>
    // 引入api


    import qs from 'qs'

    export default {
        name: "User",
        data(){
            return {

                loading: false,
                //分配角色对话框的显示和隐藏
                dialogVisible:false,
                //所有角色
                roleTableList:[],
                //当前用户具有的角色
                userRoles:[],
                queryParams:{},
                //所有的部门信息
                deptOptions:[],
                //系统状态
                statusOptions:[],
                // 级别数据字典
                levelOptions: [],
                // 背景数据字典
                backgroudOptions: [],
                // 是否参与排班
                schedulingOptions: [],
                // 性别数据字典
                sexOptions: [],
                //所有员工的信息
                userList:[],
                //总条数
                total: 0,
                pageSize: 5,
                currentPage:1,
                multipleSelection:[],
                //分配角色的用户的id
                // userId:0,
                labelPosition: 'right',
                // 是否显示弹出层
                open: false,
                // 弹出层标题
                title: '',
                    form: {
                    },
                    // 表单校验
                    rules: {
                        userName: [
                            { required: true, message: '科室名称不能为空', trigger: 'blur' }
                        ],
                        userNumber: [
                            { required: true, message: '科室编码不能为空', trigger: 'blur' }
                        ]
                    },

            }

        },
        created() {

             //加载所有部门
            this.initDept();
            //加载系统状态
            this.initStatus();
            //加载员工信息
            this.initUser();
            // 加载性别
            this.initSex();
            //加载级别
            this.initLevel();
            // 加载排班
            this.initscheduling();
            //加载背景
            this.initBackground();

        },
        methods: {

            handleUpdate(row){
                this.open=true;
                this.form=JSON.parse(JSON.stringify(row));
            },
            handleAdd(){
              this.open=true;
              this.form={};
            },
            handleSubmit(){
              this.$refs.form.validate((valid)=>{
                  if (valid){
                      this.$axios.post("/system/api/user/saveAndUpdate",qs.stringify(this.form)).then(result=>{
                          if (result.data.data){
                              this.$message.success("添加成功")
                              this.open=false
                              this.form={}
                              this.initUser()
                          }else {
                              this.$message.error("添加失败");
                          }
                      })
                  }else {
                      console.log('error submit!!')
                      return false
                  }
              })
            },


            // 取消
            cancel() {
                this.open = false
                this.title = ''
            },
            // 重置表单
            reset() {
                // this.resetForm('form')
                this.form = {
                    userId: undefined,
                    userName: undefined,
                    phone: undefined,
                    sex: '0',
                    age: 0,
                    status: '0',
                    email: undefined,
                    strong: undefined,
                    honor: undefined,
                    introduction: undefined,
                    remark: undefined,
                    schedulingFlag: '0'
                }
            },

            // 删除操作
            delPro(obj){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete(`/system/api/user/delById/${obj}`).then(result=>{
                        if (result.data.data){
                            // alert(result.data.t); // 测试弹出获取的数据信息,返回true/false
                            this.initUser();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message.error({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },


            //确认分配角色
            confirmRole() {
                //传递哪些参数？userId  roleIds
                let roleIds = [];
                this.multipleSelection.forEach(item => {
                    roleIds.push(item.roleId);
                })
                this.$axios.post("/system/api/role/confirmRole?roleIds=" + roleIds + "&userId=" + this.userId).then(result => {
                    this.dialogVisible = false;
                    this.$message.success("分配角色成功")
                })
            },
            //背景解析
            backgroundFormat(row) {
                let v = row.background;
                return this.formatDict(this.backgroudOptions, v);
            },
            handleSelectionChange(v) {
                this.multipleSelection = v;
            },
            //  排班解析
            schedulingFormat(row) {
                let v = row.schedulingFlag;
                return this.formatDict(this.schedulingOptions, v);
            },
            // 级别解析
            levelFormat(row) {
                let v = row.userRank;
                return this.formatDict(this.levelOptions, v);
            },
            // 性别字典的解析
            sexFormat(row) {
                let v = row.sex;
                return this.formatDict(this.sexOptions, v);
            },
            // 状态字典的解析
            statusFormat(row) {
                let v = row.status;
                return this.formatDict(this.statusOptions, v);
            },
            // 部门字典的解析
            deptFormat(row) {
                let v = row.deptId;
                for (let i = 0; i < this.deptOptions.length; i++) {
                    if (this.deptOptions[i].deptId == v) {
                        return this.deptOptions[i].deptName;
                    }
                }
                return "";
            },
            //分配角色弹出
            async fenRole(row) {
                this.userId = row.userId;
                //打开弹出框
                this.dialogVisible = true;
                //查询所有角色
                //当前用户具有的角色
                await this.$axios.get("system/api/role/getByUserId/" + row.userId).then(result => {
                    this.roleTableList = result.data.data.roles;
                    this.userRoles = result.data.data.userRoles;
                });
                //创建一个空数组用来存放默认数据
                let list = []
                //遍历表格的数据，再遍历需要在表格中反显的数据，两者的id一致
                this.roleTableList.forEach((item) => {
                    this.userRoles.forEach(val => {
                        if (val.roleId === item.roleId) {
                            // 把判断出来的默认表格数据push到创建的数组中
                            list.push(item)
                        }
                    })
                })
                console.log(list)
                //再遍历数组，将数据放入方法中
                list.forEach((row) => {
                    this.$refs.roleListTable.toggleRowSelection(row, true)
                })

            },
            //初始化部门
            initDept() {
                this.$axios.get("/system/api/dept/list").then(result => {
                    this.deptOptions = result.data.data;
                })
            },
            //初始化状态
            initStatus() {
                this.$axios.get("/system/api/dict/data/findByType/sys_normal_disable").then(result => {
                    this.statusOptions = result.data.data;
                })
            },
            //初始性别字典
            initSex() {
                this.$axios.get("/system/api/dict/data/findByType/sys_user_sex").then(result => {
                    this.sexOptions = result.data.data;
                })
            },
            //初始化级别
            initLevel() {
                this.$axios.get("/system/api/dict/data/findByType/sys_user_level").then(result => {
                    this.levelOptions = result.data.data;
                })
            },
            //初始化背景
            initBackground() {
                this.$axios.get("/system/api/dict/data/findByType/sys_user_background").then(result => {
                    this.backgroudOptions = result.data.data;
                })
            },
            //初始化排班
            initscheduling() {
                this.$axios.get("/system/api/dict/data/findByType/sys_yes_no").then(result => {
                    this.schedulingOptions = result.data.data;
                })
            },
            initUser() {
                this.$axios.post("/system/api/user/searchUser/" + this.currentPage + "/" + this.pageSize, this.queryParams).then(result => {
                    this.userList = result.data.data.records;
                    this.total = result.data.data.total;
                })
            },
            // 分页pageSize变化时触发
            handleSizeChange(val) {
                this.pageSize = val
                // 重新查询
                this.initUser()
            },
            // 点击上一页  下一页，跳转到哪一页面时触发
            handleCurrentChange(val) {
                this.currentPage = val
                // 重新查询
                this.initUser()
            },
            // 数据表格的多选择框选择时触发
            handleSelectionChnage(selection) {
                this.multipleSelection=selection;
                this.single = selection.length !== 1
                this.multiple = !selection.length
            },
            // 批量删除
            delLists(){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post("/system/api/user/delListById",this.multipleSelection).then(result=>{
                        if (result.data.data){
                            this.initUser();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

        }

    }
</script>

<style scoped>

</style>
